﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.IO;

namespace Pixysoft.Framework.Comet
{
    class CometMessageHelper : ICometMessageHelper
    {
        private static byte blank = 32;

        public void DoResponse(HttpResponse httpresponse, ICometMessage message)
        {
            SetResponseInformation(httpresponse, message);

            SetResponseContent(httpresponse, message.Content);
        }

        public void SetResponseInformation(HttpResponse httpresponse, ICometMessage message)
        {
            if (!string.IsNullOrEmpty(message.ContentType))
            {
                httpresponse.ContentType = message.ContentType;
            }

            if (!string.IsNullOrEmpty(message.Content_Disposition))
            {
                httpresponse.AddHeader("Content-Disposition", message.Content_Disposition);
            }

            if (!string.IsNullOrEmpty(message.Content_Length))
            {
                httpresponse.AddHeader("Content-Length", message.Content_Length);
            }
        }

        public void SetResponseContent(HttpResponse httpresponse, byte[] message)
        {
            byte[] response = message;

            if (response == null || response.Length == 0)
                response = new byte[] { blank };

            httpresponse.Clear();

            BinaryWriter writer = new BinaryWriter(httpresponse.OutputStream);

            writer.Write(response);

            writer.Flush();

            writer.Close();

            httpresponse.End();
        }



        public void SetAttachment(ICometMessage message, string filename, byte[] content)
        {
            message.ContentType = StringHelper.default_contenttype;

            message.Content_Disposition = "attachment;filename=" + HttpUtility.UrlEncode(filename, System.Text.Encoding.UTF8);

            message.Content_Length = content.Length.ToString();

            message.Filename = filename;

            message.Content = content;
        }

        public void SetImage(ICometMessage message, byte[] content)
        {
            message.ContentType = "image/gif";

            message.Content_Disposition = null;

            message.Content_Length = null;

            message.Filename = null;

            message.Content = content;
        }

        public void SetText(ICometMessage message, string content)
        {
            message.ContentType = null;

            message.Content_Disposition = null;

            message.Content_Length = null;

            message.Filename = null;

            message.Content = Pixysoft.StringCoder.StringToByte(content);
        }
    }
}
